package com.hean.activity;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AddContact extends Activity {
	private TextView tvName;
	private TextView tvPhone;
	private Button submit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addcontact);
		tvName=(TextView)this.findViewById(R.id.contact_name);
		tvPhone=(TextView)this.findViewById(R.id.contact_phone);
		submit=(Button)this.findViewById(R.id.addcontact_submit);
		
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String name=tvName.getText().toString();
				String phone=tvPhone.getText().toString();
				String path = "/mnt/sdcard/contacts.txt";
				try {
					if (validate(name, phone)) {
						PrintWriter pw = new PrintWriter(
								new OutputStreamWriter(new FileOutputStream(
										path, true), "utf-8"));
						pw.print("\n" + name + "," + phone);
						pw.close();
						Toast.makeText(AddContact.this, "添加成功", 2000);
						//添加一个返回按钮，用下面的代码
						Intent intent=new Intent(AddContact.this,Phone.class);
						startActivity(intent);
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		});
	}
	
	private boolean validate(String name, String phone) {
		return name != null && name.length() > 0 && phone != null
				&& phone.length() > 0;
	}
}
